package edu.zjut.hjg.saas.biz.service.impl;

import edu.zjut.hjg.saas.biz.dao.AdminDao;
import edu.zjut.hjg.saas.biz.model.Admin;
import edu.zjut.hjg.saas.biz.service.AdminService;
import edu.zjut.hjg.saas.biz.service.exception.ServiceException;
import edu.zjut.hjg.saas.biz.support.ServiceError;
import edu.zjut.hjg.saas.common.util.MD5Util;

public class AdminServiceImpl implements AdminService {

    private AdminDao adminDao;

    public void setAdminDao(AdminDao adminDao) {
        this.adminDao = adminDao;
    }

    @Override
    public Admin authenticate(String username, String password) {
        Admin admin = adminDao.findByUsername(username);
        if (admin != null && admin.getPassword().equals(MD5Util.toMD5(password))) {
            return admin;
        }
        return null;
    }

    @Override
    public void updatePassword(Integer id, String oldPassword, String newPassword)
            throws ServiceException {
        Admin admin = adminDao.load(id);
        if (admin == null) {
            throw new RuntimeException("admin not found for id=" + id);
        } else if (!admin.getPassword().equals(MD5Util.toMD5(oldPassword))) {
            // 原密码错误
            throw new ServiceException(ServiceError.PASSWORD_NOT_MATCH);
        }
        // 原密码匹配，修改
        admin.setPassword(MD5Util.toMD5(newPassword));
        adminDao.update(admin);
    }
}
